//
//  BCIndustryListController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/11/12.
//  Copyright © 2018年 guoshikeji. All rights reserved.
//

#import "BCIndustryController.h"

//全部产业
#import "BCIndustryAllController.h"
//项目明细
#import "BCProjectDetailsController.h"
//
#import "BCURLController.h"

//cell以及cellheader
#import "BCIndustryTopCell.h"
#import "HomeRecommendCell.h"
#import "BCIndustryAdsCell.h"
#import "CustomProjectHeaderView.h"
#import "BCIndustrySectionModel.h"

//refresh
#import "BCRefreshNormalHeader.h"
#import "BCRefreshAutoFooter.h"


//request
#import "BCIndustryDataRequest.h"

@interface BCIndustryController () <UITableViewDataSource,UITableViewDelegate,BCIndustryTopCellDelegate,BCIndustryAdsCellDelegate>

@property (nonatomic, strong) UITableView *industryTable;

/**
 *refreshHeader
 */
@property (nonatomic, strong) BCRefreshNormalHeader *refreshHeader;
/**
 *refreshAutoFooter
 */
@property (nonatomic, strong) BCRefreshAutoFooter *refreshAutoFooter;

#pragma mark - source

/**
 *topSource 及section==0时的数据源
 */
@property (nonatomic, strong) NSMutableArray <BCProjectModel *> *topSource;

/**
 *projectSource
 */
@property (nonatomic, strong) NSMutableArray <BCIndustrySectionModel *> *projectSource;


#pragma mark - requestData

/**
 *requestIndustyData
 */
@property (nonatomic, strong) BCIndustryData *requestIndustyData;

@end

@implementation BCIndustryController

- (NSMutableArray<BCProjectModel *> *)topSource {
    if (!_topSource) {
        _topSource = [NSMutableArray array];
    }
    return _topSource;
}
- (NSMutableArray <BCIndustrySectionModel*> *)projectSource {
    if (!_projectSource) {
        _projectSource = [NSMutableArray array];
    }
    return _projectSource;
}


- (BCRefreshNormalHeader *)refreshHeader {
    if (!_refreshHeader) {
        _refreshHeader = [BCRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshHeaderAction)];
    }
    return _refreshHeader;
}
- (BCRefreshAutoFooter *)refreshAutoFooter {
    if (!_refreshAutoFooter) {
        _refreshAutoFooter = [BCRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshAutoFooterLoadMoreAction) needBottomSafeArea:false];
    }
    return _refreshAutoFooter;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self.customNaviBar.leftButton setImage:nil forState:UIControlStateNormal];
//    self.customNaviBar.titleLabel.text = BCLocalizedKey(@"tabBar_industry");
    //
    [self setupSubviews];
    
    //触发请求数据
    [self.refreshHeader beginRefreshing];
}
- (void)setupSubviews {
    //all industries
//    [self.customNaviBar.rightButton setTitle:BCLocalizedKey(@"industry_button_all") forState:UIControlStateNormal];
    //
    self.industryTable = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.industryTable.dataSource = self;
    self.industryTable.delegate = self;
    self.industryTable.backgroundColor = [UIColor clearColor];
    self.industryTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.industryTable.showsVerticalScrollIndicator = false;
    [self.view addSubview:self.industryTable];
    [self.industryTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customNaviBar.mas_bottom);
        make.left.bottom.right.mas_equalTo(self.view);
    }];
    [self.industryTable registerClass:BCIndustryTopCell.class forCellReuseIdentifier:NSStringFromClass(BCIndustryTopCell.class)];
    [self.industryTable registerClass:HomeRecommendCell.class forCellReuseIdentifier:NSStringFromClass(HomeRecommendCell.class)];
    [self.industryTable registerClass:BCIndustryAdsCell.class forCellReuseIdentifier:NSStringFromClass(BCIndustryAdsCell.class)];
    [self.industryTable registerClass:CustomProjectHeaderView.class forHeaderFooterViewReuseIdentifier:NSStringFromClass(CustomProjectHeaderView.class)];
    //
    [self.industryTable setMj_header:self.refreshHeader];
    [self.view layoutIfNeeded];
}

- (void)didClickedNaviRightButton {
    [self toAllIndustriesAction];
}

#pragma mark - refresh
- (void)refreshHeaderAction {
    if (self.isLoadedData) {
        [self requestIndustryDataInit:false refresh:true];
    }else {
        [self requestIndustryDataInit:true refresh:false];
    }
}


#pragma mark - UITableViewDataSource,UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSInteger numbers = 0;
    numbers += 1;//顶部的section
    if (self.isLoadedData) {
        numbers += self.projectSource.count;
    }else {
        numbers += 2;//预加载的两个section
    }
    return numbers;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return self.topSource.count;
    }else {
        if (self.isLoadedData) {
            BCIndustrySectionModel *sectionModel = self.projectSource[section-1];
            //
            NSInteger projectCounts = sectionModel.projects.count;
            NSInteger adCount = sectionModel.hasAds?1:0;//是否有广告
            return projectCounts+adCount;
        }else {
            return 2;//每个section 预加载2个cell
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section!=0) {
        BCProjectModel *model;
        if (self.isLoadedData) {
            BCIndustrySectionModel *sectionModel = self.projectSource[indexPath.section-1];
            //在此判断是否有广告
            if (sectionModel.hasAds) {
                if (sectionModel.projects.count<=indexPath.row) {//此时返回广告cell
                    BCIndustryAdsCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCIndustryAdsCell.class)];
                    cell.delegate = self;
                    cell.sectionModel = sectionModel;
                    return cell;
                }
            }
            model = sectionModel.projects[indexPath.row];
        }
        HomeRecommendCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(HomeRecommendCell.class)];
        cell.cellData = model;
        cell.tableView = tableView;
        return cell;
    }else {
        BCIndustryTopCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass(BCIndustryTopCell.class)];
        cell.delegate = self;
        cell.cellData = self.topSource[indexPath.row];
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section==0) {
        return [BCIndustryTopCell defaultHeight];
    }else {
        if (self.isLoadedData) {
            BCIndustrySectionModel *sectionModel = self.projectSource[indexPath.section-1];
            if (sectionModel.hasAds&&sectionModel.projects.count<=indexPath.row) {
                return [BCIndustryAdsCell heightWithWidth:tableView.frame.size.width];
            }
        }
        return [HomeRecommendCell defaultHeight];
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section!=0) {
        BCIndustrySectionModel *sectionModel;
        if (self.isLoadedData) {
            sectionModel = self.projectSource[section-1];
        }
        CustomProjectHeaderView *header = [[CustomProjectHeaderView alloc] initWithReuseIdentifier:NSStringFromClass(CustomProjectHeaderView.class)];
        header.isLoadedData = self.isLoadedData;
        header.title = sectionModel.title;
        return header;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section!=0) {
        if (self.isLoadedData) {
            BCIndustrySectionModel *sectionModel = self.projectSource[section-1];
            if (sectionModel.projects.count) {
                return [CustomProjectHeaderView defaultHeight];
            }else {
                return 0.0;
            }
        }else {
            return [CustomProjectHeaderView defaultHeight];
        }
    }
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footer = [UIView new];
    footer.backgroundColor = [UIColor separatorViewColor];
    return footer;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10.0f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section!=0) {
        BCProjectModel *model;
        if (self.isLoadedData) {
            BCIndustrySectionModel *sectionModel = self.projectSource[indexPath.section-1];
            if (sectionModel.projects.count>indexPath.row) {
                model = sectionModel.projects[indexPath.row];
                [self toProjectDetailsAction:model];
            }
        }
    }
}

#pragma mark - BCIndustryAdsCellDelegate
/**
 视图中的广告被点击了
 */
- (void)industryAdsCell:(BCIndustryAdsCell *)cell didSelectedAdModel:(BCIndustryDataTitleGroupAdModel *)adModel {
    if (adModel.ad_url.length) {
        BCURLController *urlVC = [BCURLController new];
        urlVC.urlString = adModel.ad_url;
        [self.navigationController pushViewController:urlVC animated:true];
    }
}

#pragma mark - BCIndustryTopCellDelegate
- (void)industryTopCellDidClickedBuyButton:(BCProjectModel *)model {
    [self toProjectDetailsAction:model];
}

#pragma mark - request
/**
 请求数据
 */
- (void)requestIndustryDataInit:(BOOL)init refresh:(BOOL)refresh {
    self.industryTable.mj_footer = nil;
    //
    BCIndustryDataRequest *request = [BCIndustryDataRequest new];
    request.reg_id = [BCUserManager sharedUser].reg_id;
    //
    WEAK_SELF
    [request didRequestCompleted:^{
        [wself.refreshHeader endRefreshing];
    }];
    [request didRequestSuccessed:^(id result, id page) {
        BCIndustryDataResponse *resp = result;
        [wself reloadIndustryData:resp];
    }];
    [request didRequestFailed:^(NSError *error) {
        if (error&&wself.view) {
            if (init) {
                [wself.industryTable bc_showError:error needRefresh:true refreshTitle:nil target:wself refreshAction:@selector(requestInitErrorAction)];
            }
            
            NSString *errMsg = error.domain;
            [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
        }
    }];
    [request requestServer];
}
- (void)requestInitErrorAction {
    [self.industryTable bc_hiddenError];
    [self.refreshHeader beginRefreshing];
}

//请求数据成功后 重新加载数据
- (void)reloadIndustryData:(BCIndustryDataResponse *)resp {
    self.requestIndustyData = resp.data;
}
- (void)setRequestIndustyData:(BCIndustryData *)requestIndustyData {
    _requestIndustyData = requestIndustyData;
    if (requestIndustyData) {
        self.isLoadedData = true;
        //title和右上角按钮title
        self.customNaviBar.titleLabel.text = requestIndustyData.flow.title;
        [self.customNaviBar.rightButton setTitle:requestIndustyData.flow.reght forState:UIControlStateNormal];
        [self.customNaviBar layoutSubviews];
        //重构数据
        [self.topSource removeAllObjects];
        //top
        NSArray *selectedData = requestIndustyData.selected.data;
        BCIndustrySelectedTextModel *selectedText = requestIndustyData.selected.text;
        if (selectedData.count) {
            for (int i=0; i<selectedData.count; i++) {
                BCProjectModel *project = selectedData[i];
                //
                project.repayCaption = selectedText.repay;
                project.countdownMess = selectedText.mess;
                project.not_buy = selectedText.not_buy;
                [self.topSource addObject:project];
            }
        }
        //发展之星、预购产业等
        [self.projectSource removeAllObjects];
        //
        BCIndustryDataTitleGroup *develop = requestIndustyData.develop;
        if (develop.data.count || develop.ads.count) {
            BCIndustrySectionModel *section = [BCIndustrySectionModel new];
            section.title = develop.title;
            for (int i=0; i<develop.data.count; i++) {
                BCProjectModel *project = develop.data[i];
                //
                project.repayCaption = develop.text.repay;
                
                [section.projects addObject:project];
            }
            //ad
            section.ads = develop.ads;
            //
            [self.projectSource addObject:section];
        }
        //
        BCIndustryDataTitleGroup *advance = requestIndustyData.advance;
        if (advance.data.count || advance.ads.count) {
            BCIndustrySectionModel *section = [BCIndustrySectionModel new];
            section.title = advance.title;
            for (int i=0; i<advance.data.count; i++) {
                BCProjectModel *project = advance.data[i];
                //
                project.repayCaption = advance.text.repay;
                project.advance_taking = advance.text.advance_taking;
                
                [section.projects addObject:project];
            }
            //ad
            section.ads = advance.ads;
            //
            [self.projectSource addObject:section];
        }
        
//        [self.refreshAutoFooter setTitle:requestHomeData.flow.bottom forState:MJRefreshStateNoMoreData];
//        [self.industryTable setMj_footer:self.refreshAutoFooter];
//        [self.refreshAutoFooter endRefreshingWithNoMoreData];
        
    }else {
        self.isLoadedData = false;
    }
    //
    [self.industryTable reloadData];
}



#pragma mark - to actions
//跳转去全部产业
- (void)toAllIndustriesAction {
    BCIndustryAllController *all = [BCIndustryAllController new];
    [self.navigationController pushViewController:all animated:true];
}
//项目明细
- (void)toProjectDetailsAction:(BCProjectModel *)model {
    BCProjectDetailsController *detail = [BCProjectDetailsController new];
    detail.projectId = [NSString stringWithFormat:@"%@",@(model.project_id)];
    [self.navigationController pushViewController:detail animated:true];
}

@end
